package com.qf.erpb.sale.controller;

import com.alibaba.excel.EasyExcel;
import com.qf.erpb.core.common.JsonResult;
import com.qf.erpb.core.vo.PageVO;
import com.qf.erpb.sale.entity.SaleOrder;
import com.qf.erpb.sale.entity.SysUserReadListener;
import com.qf.erpb.sale.param.SaleOrderParam;
import com.qf.erpb.sale.service.SaleOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 销售订单表(SaleOrder)表控制层
 *
 * @author makejava
 * @since 2023-12-18 17:08:10
 */
@RestController
@RequestMapping("/saleOrder")
@Api(tags = "销售管理接口")
@CrossOrigin
public class SaleOrderController {
    @Resource
    private SaleOrderService saleOrderService;

    @ApiOperation("Echarts视图1")
    @GetMapping("/echarts1")
    public JsonResult showEcharts1() {
        List<Map<String, Object>> resultMap = saleOrderService.findmoneypeople1();

        ArrayList<Object> nameList = new ArrayList<>();
        ArrayList<Object> priceList = new ArrayList<>();
        resultMap.forEach(map -> {
            nameList.add(map.get("contact_people"));
            priceList.add(map.get("money"));
        });
// 返回数据格式
        HashMap<String, Object> map = new HashMap<>();
        map.put("sexX", nameList);
        map.put("sexY", priceList);
        return JsonResult.ok(map);
    }

    @ApiOperation("Echarts视图")
    @GetMapping("/echarts")
    public JsonResult showEcharts() {
        List<Map<String, Object>> resultMap = saleOrderService.findmoneypeople();
        ArrayList<String> sexList = new ArrayList<>();
        ArrayList<Object> numList = new ArrayList<>();
        resultMap.forEach(map -> {
            String sex = (String) map.get("sex");
            if (sex.equals("0")) {
                sexList.add("男");
            } else {
                sexList.add("女");
            }
            Object num = map.get("num");
            numList.add(num);
        });


        HashMap<String, Object> map = new HashMap<>();
        map.put("sexX", sexList);
        map.put("sexY", numList);
        /**
         * {
         *     sexX: [男,女],
         *     sexY: [81,29]
         * }
         */
        return JsonResult.ok(map);
    }

    @ApiOperation("Map查询一个")
    @PostMapping("/selectOne")
    public JsonResult selectOne(Long id) {

        return JsonResult.ok(this.saleOrderService.selectOne(id));
    }

    @ApiOperation("Map查询全部")
    @PostMapping("/selectAll")
    public JsonResult selectAll() {
        return JsonResult.ok(this.saleOrderService.selectAll());
    }

    @ApiOperation("删除单个")
    @PostMapping("/del")
    public JsonResult del(Integer id) {
        saleOrderService.removeById(id);
        return JsonResult.ok();
    }

    @ApiOperation("修改信息")
    @PostMapping("/update")
    public JsonResult update(@RequestBody SaleOrder saleOrder) {
        saleOrderService.updateById(saleOrder);
        return JsonResult.ok();
    }

    @ApiOperation("添加")
    @PostMapping("/add")
    public JsonResult add(@RequestBody SaleOrder saleOrder) {
        saleOrderService.save(saleOrder);
        return JsonResult.ok();
    }

    @ApiOperation("批量删除")
    @PostMapping("/delbath")
    public JsonResult delbath(@RequestBody List<Long> id) {
        saleOrderService.removeByIds(id);
        return JsonResult.ok();
    }

    @ApiOperation("查询id")
    @PostMapping("/selid")
    public JsonResult selid(Integer id) {
        SaleOrder saleOrder = saleOrderService.getById(id);
        return JsonResult.ok(saleOrder);
    }

    @ApiOperation("模糊查询分页")
    @PostMapping("/selpage")
    public JsonResult selpage(SaleOrderParam param) {
        PageVO<SaleOrder> pageVO = saleOrderService.pageSaleOrder(param);
        return JsonResult.ok(pageVO);
    }

    /**
     * upload file
     */
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile img, HttpServletRequest request) throws IOException {
        // 1.获得上传的对象 参数img就是文件对象

        // 2. 获得最终上传的目的地路径(上传至服务器中当前项目下)
        // 通过servlet方法获得路径,即最终上传到Tomcat的/upload
        String realPath = request.getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        // 2.1 将最终目的文件夹创建出来
        File file = new File(realPath);
        // 判断该文件是否存在
        if (!file.exists()) {
            // 不存在则创建出
            file.mkdir();
        }
        // 2.2 获得文件名
        /*
         * 文件名重复时不能重复上传文件
         */
        String fileName = img.getOriginalFilename();
        System.out.println(fileName);
        /*
         * 根据.拆分字符串,获得文件后缀名
         */
        String[] split = fileName.split("\\.");
        System.out.println(Arrays.toString(split));
        String suffix = split[split.length - 1];
        // 以当前毫秒值为文件名
        long prefix = new Date().getTime();
        // 组装文件名
        String newFileName = prefix + "." + suffix;
        System.out.println("新的文件名 : " + newFileName);
        // 2.3 确定上传路径
        File newFile = new File(file, newFileName);
        // 3. 用工具上传
        FileUtils.writeByteArrayToFile(newFile, img.getBytes());
        // 4 返回路径,测试使用,放查看是否上传成功
        // String path = "http://localhost:8081/upload/"+newFileName;
        System.out.println("http://localhost:8888/upload/" + newFileName);

        HttpSession session = request.getSession();
        SaleOrder sysUser = (SaleOrder) session.getAttribute("sysUser");

        SaleOrder user = new SaleOrder();
        user.setId(sysUser.getId());
        user.setCustomName("http://localhost:8888/upload/" + newFileName);
        // TODO 更新数据库 这id对应的头像地址
        return JsonResult.ok("http://localhost:8888/upload/" + newFileName);
    }


    @ApiOperation("excal导入")
    @PostMapping("/import")
    public JsonResult importExcel(MultipartFile file) throws IOException {
        // 别忘了给SysUserReadListener构造方法传入SysUserService对象
        EasyExcel.read(file.getInputStream(), SaleOrder.class, new SysUserReadListener(saleOrderService)).sheet().doRead();
        return JsonResult.ok();
    }

    /**
     * 导出excel
     */
    @ApiOperation("excal导出")
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 调用业务层,查询全部数据
        List<SaleOrder> list = saleOrderService.query().list();
        // 下面这个注释是前端使用方式1,即a标签发请求时采用
        // response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("系统用户信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + "info" + ".xlsx");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), SaleOrder.class).autoCloseStream(Boolean.FALSE).sheet("系统用户信息").doWrite(list);
    }


}

